// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package traffic

import (
	"log"

	"apiote.xyz/p/szczanieckiej/config"

	"fmt"
	"os"
	"path/filepath"
	"time"

	"git.sr.ht/~sircmpwn/go-bare"
)

func getLastFeedsUpdated(feedsPath string) (map[string]time.Time, error) {
	lastUpdates := map[string]time.Time{}

	updatesFilename := filepath.Join(feedsPath, "updated.bare")
	updatesFile, err := os.Open(updatesFilename)
	if err != nil {
		return lastUpdates, fmt.Errorf("while opening updates file: %w", err)
	}
	defer updatesFile.Close()

	var lastUpdated map[string]string
	err = bare.UnmarshalReader(updatesFile, &lastUpdated)
	if err != nil {
		return lastUpdates, fmt.Errorf("while unmarshaling updates file: %w", err)
	}

	for feedID, st := range lastUpdated {
		t, err := time.Parse(time.RFC3339, st)
		if err != nil {
			return lastUpdates, fmt.Errorf("while parsing update time for %s: %w", feedID, err)
		}
		lastUpdates[feedID] = t
	}
	return lastUpdates, nil
}

func GetFeedInfos(t *Traffic, cfg config.Config) (map[string]FeedInfo, map[string]time.Time, error) {
	feedInfos := map[string]FeedInfo{}
	lastUpdates, err := getLastFeedsUpdated(cfg.FeedsPath)
	if err != nil {
		return feedInfos, lastUpdates, fmt.Errorf("while getting last update dates: %w", err)
	}

	for id := range t.Feeds {
		versionCode, _, err := ParseDate("", id, t)
		if err != nil {
			log.Printf("while parsing date for %s: %v", id, err)
			continue
		}

		feedInfo, err := getFeedInfo(cfg.FeedsPath, id, versionCode)
		if err != nil {
			log.Printf("while getting feed info for %s: %v", id, err)
			continue
		}

		feedInfos[id] = feedInfo
	}
	return feedInfos, lastUpdates, nil
}
